package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.base.core.utils.stringUtil.StringUtil;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.LuLianSupplierInquiryOrder;
import com.aiti.lulian.entity.LuLianSupplierInquiryOrderRequest;
import com.aiti.lulian.entity.request.BuyerSellRequest;
import com.aiti.lulian.entity.response.inquiryorder.BuyerBackGroupListResp;
import com.aiti.lulian.mapper.LuLianEnterpriseMapper;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ILuLianSupplierInquiryOrderService;
import com.aiti.lulian.vo.XunJiaRepsonse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName LuLianSupplierInquiryOrderController
 * @Description
 * @Author diaozhende
 * @Date 2024/6/12 0012 15:28
 */
@RestController
@RequestMapping("/supplierInquiryOrder")
public class LuLianSupplierInquiryOrderController extends WebController {

    @Resource
    private ILuLianSupplierInquiryOrderService supplierInquiryOrderService;

    @Autowired
    private ILuLianEnterpriseService luLianEnterpriseService;

    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;

    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;

    /**
     * 多参数查询
     *
     * @param supplierInquiryOrder 查询参数
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:30
     * @author diaozhende
     */
    @GetMapping
    public Message queryByParams(LuLianSupplierInquiryOrder supplierInquiryOrder) {
        List<LuLianSupplierInquiryOrder> supplierInquiryOrderList = supplierInquiryOrderService.queryByParams(supplierInquiryOrder);
        return Message.success(supplierInquiryOrderList);
    }

    /**
     * 分页查询
     *
     * @param page                 当前页
     * @param pageSize             每页显示条数
     * @param supplierInquiryOrder 查询参数
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:32
     * @author diaozhende
     */
    @GetMapping("/queryPage")
    public Message queryPage(Integer page, Integer pageSize, LuLianSupplierInquiryOrder supplierInquiryOrder) {
        try {
            if (page == null || pageSize == null) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
//            String userId = findUserId();
//            if (userId != null) {
//                supplierInquiryOrder.setCreator(userId);
//            } else {
//                System.out.println("------------------未注册------------------");
//                return Message.fail("请注册登录！");
//            }
            if (supplierInquiryOrder == null){
                supplierInquiryOrder = new LuLianSupplierInquiryOrder();
            }
            supplierInquiryOrder.setIsDel("0");
            supplierInquiryOrder.setIsExpired("2");
            return Message.success(supplierInquiryOrderService.queryPage(page, pageSize, supplierInquiryOrder));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 后台分页查询（根据userId筛选）
     *
     * @param page                 当前页
     * @param pageSize             每页显示条数
     * @param supplierInquiryOrder 查询参数
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:32
     * @author diaozhende
     */
    @GetMapping("/queryPageBackend")
    public Message queryPageBackend(Integer page, Integer pageSize, LuLianSupplierInquiryOrder supplierInquiryOrder) {
        try {

            if (page == null || pageSize == null || supplierInquiryOrder == null) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            String userId = findUserId();
            System.out.println("========="+supplierInquiryOrder.getIsExpired()+"--user----"+userId);
            if (userId != null) {
                supplierInquiryOrder.setCreator(userId);
            } else {
                System.out.println("------------------未注册------------------");
                return Message.fail("请注册登录！");
            }
            return Message.success(supplierInquiryOrderService.queryPage(page, pageSize, supplierInquiryOrder));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 各条件查询的统计计数
     *
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/7/13
     * @author WongMZ
     */
    @GetMapping("/queryCount")
    public Message queryCount() {
        try {
            String userId = findUserId();
            if (userId != null) {
                return Message.success(supplierInquiryOrderService.queryCount(userId));
            } else {
                System.out.println("------------------未注册------------------");
                return Message.fail("请注册登录！");
            }
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    @GetMapping("/show")
    public Message show(int page, int pageSize, LuLianSupplierInquiryOrder supplierInquiryOrder) {
        Page<LuLianSupplierInquiryOrder> pageData = supplierInquiryOrderService.queryPage(page, pageSize, supplierInquiryOrder);
        List<LuLianSupplierInquiryOrder> list = pageData.getRecords();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCreator() != null) {
                LuLianEnterprise enterprise = luLianEnterpriseMapper.selectOne(new QueryWrapper<LuLianEnterprise>().eq("creator", list.get(i).getCreator()));
                if (enterprise != null) {
                    list.get(i).setEnterpriseName(enterprise.getBaseName());
                }
            }
        }
        pageData.setRecords(list);
        return Message.success(pageData);
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:37
     * @author diaozhende
     */
    @GetMapping("/queryById")
    public Message queryById(String id) {
        LuLianSupplierInquiryOrderRequest supplierInquiryOrder = supplierInquiryOrderService.queryById(id);
        return Message.success(supplierInquiryOrder);

    }

    /**
     * 根据baseId进行回显
     *
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/7/13
     * @author WongMZ
     */
    @GetMapping("/queryByBaseId/{baseId}")
    public Message queryByBaseId(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            return Message.success(supplierInquiryOrderService.queryByBaseId(baseId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 发布招募单
     *
     * @param supplierInquiryOrder 新增数据
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:36
     * @author diaozhende WongMZ
     */
    @PostMapping
    public Message save(@RequestBody LuLianSupplierInquiryOrder supplierInquiryOrder) {
        try {
            if (supplierInquiryOrder == null) {
                logger.error("新增异常：===》入参异常");
                return Message.fail("入参异常");
            }
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                supplierInquiryOrder.setCreator(userId);
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterprise> enterpriseWrapper = new LambdaQueryWrapper<>();
            enterpriseWrapper.in(LuLianEnterprise::getBaseId, enterpriseIds);
            int count = luLianEnterpriseService.count(enterpriseWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            }
            //进行数据保存
            int res = supplierInquiryOrderService.saveData(supplierInquiryOrder);
            if (res > 0) {
                return Message.success();
            } else {
                System.out.println("--fail--"+res);
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 根据ID修改
     *
     * @param supplierInquiryOrder 修改数据
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:39
     * @author diaozhende WongMZ
     */
    @PutMapping
    public Message updateById(@RequestBody LuLianSupplierInquiryOrder supplierInquiryOrder) {
        try {
            if (supplierInquiryOrder == null) {
                logger.error("更新异常：===》入参异常");
                return Message.fail("入参异常");
            }
            int res = supplierInquiryOrderService.updateDataById(supplierInquiryOrder);
            if (res > 0) {
                System.out.println("res--"+res);
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Message.fail(e.getMessage());
        }
    }


    /**
     * 根据ID删除
     *
     * @param id ID
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/12 0012 15:40
     * @author diaozhende
     */
    @DeleteMapping("/{id}")
    public Message deleteById(@PathVariable("id") String id) {
        supplierInquiryOrderService.removeById(id);
        return Message.success();
    }

    /**
     * 招募单立即报价回显
     *
     * @param recruitId 招募单Id
     * @return
     */
    @GetMapping("/queryShowSupplierInquiryOrderRecruit/{recruitId}/{type}")
    public Message queryShowSupplierInquiryOrderRecruit(@PathVariable("recruitId") String recruitId,@PathVariable("type") String type,
                                                        @RequestParam(value = "userId", required = false) String userId) {
        String currentUserId = findUserId();
        if (StringUtil.isBlank(currentUserId)) {
            currentUserId = userId;
            if (StringUtil.isBlank(currentUserId)) {
                return Message.fail("请登陆");
            }
        }
        return supplierInquiryOrderService.queryShowSupplierInquiryOrderRecruit(recruitId, currentUserId,type);
    }

    /**
     * 我的报名
     *
     * @return
     */
    @GetMapping("/querySellSupplierInquiryOrderRecruit")
    public Message querySellSupplierInquiryOrderRecruit(BuyerSellRequest buyerSellRequest){
        String userId = findUserId();
        if(StringUtil.isBlank(userId)){
            return Message.fail("请登陆");
        }
        Integer pageSize = buyerSellRequest.getPageSize();
        Integer pageNum = buyerSellRequest.getPageNum();
        Page<BuyerBackGroupListResp> page = this.startPage(pageNum, pageSize);
        List<BuyerBackGroupListResp> buyerBackGroupListResps = supplierInquiryOrderService.querySellSupplierInquiryOrderRecruit(userId,page,buyerSellRequest.getType());
        return Success(getPageResult(buyerBackGroupListResps,pageNum,pageSize,(int)page.getTotal()));
    }

    /**
     * 应慕管理
     *
     * @return
     */
    @GetMapping("/queryBuyerInquiryOrderRecruit")
    public Message queryBuyerInquiryOrderRecruit(BuyerSellRequest buyerSellRequest){
        String userId = findUserId();
        if(StringUtil.isBlank(userId)){
            return Message.fail("请登录！");
        }
        Integer pageSize = buyerSellRequest.getPageSize();
        Integer pageNum = buyerSellRequest.getPageNum();
        Page<LuLianSupplierInquiryOrder> page = this.startPage(pageNum, pageSize);
        List<XunJiaRepsonse> buyerBackGroupListResps = supplierInquiryOrderService.queryBuyerInquiryOrderRecruit(userId,page);
        return Success(getPageResult(buyerBackGroupListResps,pageNum,pageSize,(int)page.getTotal()));
    }

    @GetMapping("/queryZmInfoById/{id}")
    public Message queryZmInfoById(@PathVariable("id") String id) {
        LuLianSupplierInquiryOrder luLianSupplierInquiryOrder = supplierInquiryOrderService.queryZmById(id);
        return Message.success(luLianSupplierInquiryOrder);
    }

    /**
     * 小程序端查询进行中和已截止的数据
     * @return
     */
    @GetMapping("/queryStataus")
    public Message queryStataus(){
        String userId = findUserId();
        return supplierInquiryOrderService.queryStataus(userId);
    }
}